﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Channels;
using System.ServiceModel.Web;
using System.Text;
using Kugar.Core;
using Kugar.Core.BaseStruct;
using Kugar.Core.Data.MSSQLHelper;
using Kugar.ERPFramework.BLLInterface;
using Kugar.Core.ExtMethod;
using System.IO;
using Kugar.ERPFramework.Entity;
using System.Reflection;
using Kugar.ERPFramework.ServiceSystemBLL;
using System.Runtime.Remoting.Messaging;


namespace Kugar.ERPFramework.Service
{
    // 注意: 使用“重构”菜单上的“重命名”命令，可以同时更改代码、svc 和配置文件中的类名“Service1”。
    // 注意: 为了启动 WCF 测试客户端以测试此服务，请在解决方案资源管理器中选择 Service1.svc 或 Service1.svc.cs，然后开始调试。
    [ServiceBehavior(InstanceContextMode = InstanceContextMode.Single)]
    public class PlatformService : MarshalByRefObject, ISystemService
    {
        private static List<IProject> _cacheProjectList = new List<IProject>();

        public PlatformService()
        {
            EnumProject();
        }

        public string Connect(string key)
        {
            var matchKey = "";

            if (matchKey.SafeEquals(key))
            {
                return OperationContext.Current.SessionId;
            }
            else
            {
                throw new Exception("通信密钥错误,请查看服务器配置项");
            }
        }

        public ProjectInfo[] GetProjectList()
        {
            return _cacheProjectList.Select(x=>x.Info).ToArray();
        }

        public IProject GetProjectByID(string projectID)
        {
            return _cacheProjectList.FirstOrDefault(x => x.Info.ProjectID == projectID);
        }

        public void SetCurrentInstance(string projectID, string instanceID)
        {
            var project = GetProjectByID(projectID);

            var instance= project.GetInstanceByID(instanceID);

            ServiceBroker.Default.CurrentSession.CurrentInstance = instance;
        }

        //注册项目
        public void RegistrProject(string path)
        {

        }

        //枚举当前服务器下已安装的项目文件夹
        private void EnumProject()
        {
            var projectPath =Path.Combine(AppDomain.CurrentDomain.BaseDirectory,"Projects");

            var projectDirs = Directory.GetDirectories(projectPath);

            if (projectDirs!=null && projectDirs.Length>0)
            {
                foreach (var dir in projectDirs)
                {
                    if (File.Exists(Path.Combine(dir,"Project.kprj")))
                    {
                        RegistrProject(dir);
                    }
                    
                }

            }
        }

        //加载项目
        private void LoadProject(string path)
        {

        }
    }

    /// <summary>
    ///     项目实例的加载运行器,运行在单独的AppDomain中
    /// </summary>
    public class ProjectLauncher:MarshalByRefObject,IProjectInstance
    {
        public ProjectLauncher(string projectPath,string intanceName)
        {
            var info = new ProjectInstanceInfo();
            info.InstanceID = Guid.NewGuid().ToStringEx();
            info.InstanceName = intanceName;
            info.ProjectID = Project.Info.ProjectID;

            InstanceInfo = info;

            BLLServiceBroker.Default.SetProject(projectPath,info.InstanceID);
        }

        public ProjectInstanceInfo InstanceInfo { get; private set; }

        public ResultReturn Execute(string moduleID, string methodID, params object[] paramList)
        {
            return BLLServiceBroker.Default.GetModuleControler(moduleID).Execute(methodID, paramList);
        }

        public ICustomBLLModule[] GetBLLList()
        {
            throw new NotImplementedException();
        }

        public ResultReturn<LoginUserInfo> Login(string userName, string pw)
        {
            if (string.IsNullOrWhiteSpace(userName))
            {
                return new ResultReturn<LoginUserInfo>(false, "用户名不能为空");
            }

            

            

            pw = pw.MD5_32();

            var ret=BLLServiceBroker.Default.SystemModule.Login(userName, pw,ip);

            if (ret.IsSuccess)
            {
                return BLLServiceBroker.Default.SystemModule.GetUserInfoByID(ret.ReturnData);
            }
            else
            {
                return new ResultReturn<LoginUserInfo>(false,"登录失败,请检查用户名或密码");
            }
        }

        public ResultReturn Logout()
        {
            throw new NotImplementedException();
        }

        public ResultReturn<string[]> GetUserNameList()
        {
            return BLLServiceBroker.Default.SystemModule.GetUserNameList();
        }

        public ResultReturn BackupDatabase()
        {
            throw new NotImplementedException();
        }

        public ILoginUserManager UserManager { get; private set; }

        public ResultReturn GetPermissionList()
        {
            throw new NotImplementedException();
        }

        public IProject Project { get; private set; }

        public IPAddress CurrentIPAddress
        {
            get 
            {
                var context = OperationContext.Current;
                //获取传进的消息属性
                var properties = context.IncomingMessageProperties;
                //获取消息发送的远程终结点IP和端口
                var endpoint = properties[RemoteEndpointMessageProperty.Name] as RemoteEndpointMessageProperty;

                IPAddress ip;

                if (endpoint == null || string.IsNullOrWhiteSpace(endpoint.Address))
                {
                    ip = IPAddress.None;
                }
                else
                {
                    ip = IPAddress.Parse(endpoint.Address);
                }

                return ip;
            }
        }

        //public CallContext ServerCallContext { get { return CallContext.; } }

        public object ClientCallContext { get { return null; } }

        public SQLDataHelper CurrentConnection { get; }

        public ResultReturn<ICustomBLLModule> GetModuleByName(string moduleName)
        { 
            
        }



        public ResultReturn<T> GetModuleByName<T>(string moduleName) where T : ICustomBLLModule
        {
            throw new NotImplementedException();
        }

        public object GetOtherConnection(string connectionName = null)
        {
            throw new NotImplementedException();
        }

        public BLLInterface.Session.SessionItem Session
        {
            get { throw new NotImplementedException(); }
        }
    }




}
